<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use app\common\model\Job;
use app\common\model\DataVideo;
class Index extends Controller{
    protected $redis;
    private $job='';
    private $data = 'aweme_list';
    public function __construct()
    {
        parent::__construct();
       /* $this->redis = new \Redis;
        $redisConf = config('redis_config');
        $this->redis->connect($redisConf['host'], $redisConf['port']);
        $this->redis->auth($redisConf['auth']);*/
    }
    public function index(){
        $data=file_get_contents('php://input');
        $data=str_replace('%7B%','{',$data);
        $data=str_replace('%7D%','}',$data);
        $data=str_replace('%22','"',$data);
        $data=str_replace('%20',' ',$data);

        //print_r($data);die;
        //print_r(json_decode($data,true));die;

        //$platform=$data['platform'];
        $data=json_decode($data,true);
        $dataJson=$data['dataJson'];
        if(isset($dataJson[$this->data])){
            $videoList=$dataJson[$this->data];
        }
        else{
            $videoList=[];
        }
        //dump($videoList);die;
        //$this->redis->hSet('job_status',$this->job,1);
       /* $jobStatus = $this->redis->hGet('job_status', $this->job);
        if ($jobStatus != 1) {
            return json(['code'=>-1,'msg'=>'采集开关关闭']);//采集开关关闭时
        }*/
       /* $jobModel = new Job();
        $jobInfo = $jobModel->where(['id' => $this->job])->find();//获取任务配置信息*/
        $jobInfo=[];
        //开始拼装数据
        $insertData = [];
        if (!empty($videoList)) {
            $this->createData($data, $jobInfo, $jobRedisData, $insertData);//对源数据进行对应入库
            if (!empty($insertData)) {
                //当实际采集数据大于等于计划采集数据量时设置redis开关值
                /*if (($jobRedisData['planned_quantity'] - $jobRedisData['real_quantity']) <= 0) {
                    $this->redis->hSet('job_status', $this->job, 2);//正常完成值为2
                    $jobRedisData['finsh_time'] = date('Y-m-d H:i:s');//正常完成时间记录
                }
                $this->redis->hSet('jobHash', $this->job, json_encode($jobRedisData));*/
                return json(['code'=>1,'msg'=>'【TikTok采集成功】本次采集入库数据条数为【' . count($insertData) . '】']);

            } else {
                return json(['code'=>1,'msg'=>'【TikTok执行成功】本次采集无符合要求的数据入库!']);

            }
        }
        else{
            return json(['code'=>1,'msg'=>'【TikTok执行成功】本次采集没有采集到数据!']);
        }

    }
    //旧版的接口
    private function createData($allData,$jobInfo, &$jobRedisData, &$insertData){
        $platform=$allData['platform'];
        $dataJson=$allData['dataJson'];
        $videoList=$dataJson[$this->data];
        $videoModel= new DataVideo();
        //print_r($allData);die;
        foreach($videoList as $val){
            //视频评论、点赞、分享数
            $data['thumb_num'] = $val['statistics']['digg_count'];//点赞数
            $data['comment_num'] = $val['statistics']['comment_count'];//评论数
            $data['share_num'] = $val['statistics']['share_count'];//分享数
            $data['watch_num'] = $val['statistics']['play_count'];//播放数
            //验证视频是否符合采集需求
            /*$validateRes = $this->validateNum($data,$jobInfo);
            if ($validateRes == false) {
                continue;
            }*/

            $videoData['id']=com_create_guid();//生成唯一UUID

            $videoData['paltform']=$platform;
            $videoData['paltform_vid']=$val['video']['download_addr']['uri'];
            $videoData['paltform_uid']='';
            $videoData['paltform_uname']='';
            $videoData['paltform_uhead']='';

            //判断是否 已经存在
            $isExist = $videoModel->field('id')->where([
                'paltform_vid' => $videoData['paltform_vid']
            ])->find();
            if ($isExist) {
                continue;
            }


            $videoData['video_title']=$val['music']['title'];
            $videoData['videocover_link']=$val['video']['cover']['url_list'][0];
            $videoData['video_link']=$val['video']['play_addr']['url_list'][0];

            $videoData['video_duration'] = $val['video']['duration'] * 1000;//视频时长【微妙】

            $videoData['video_width']=$val['video']['width'];
            $videoData['video_height']=$val['video']['height'];

            $videoData['collect_num']=0;
            $videoData['unlike_num']=0;
            if ($videoData['video_duration']/1000 <= 90) {
                //$jobRedisData['smallvideo_num'] += 1;//小视频数量+1
                $videoData['is_small'] = 1;
            } else {
                //$jobRedisData['shortvideo_num'] += 1;//短视频数量+1
                $videoData['is_small'] = 0;
            }
            $videoData['validity_period']='';
            $videoData['video_type']='';
            $videoData['indescription']='';
            $videoData['video_tag']='';
            $videoData['publish_date']=date('Y-m-d H:i:s',$val['create_time']);
            $videoData['share_url']=$val['share_url'];
            $videoData['video_widhei_type'] = getVideoSizeType($videoData['video_width'], $videoData['video_height']);//判断视频宽高类型



            $videoData['create_by']='';
            $videoData['create_date']=date('Y-m-d H:i:s');
            $videoData['update_by']='';
            $videoData['update_date']=date('Y-m-d H:i:s');

            $insertData[] = $videoData;

        }

        $videoModel->isUpdate(false)->saveAll($insertData, false);
    }
    //新版的接口
    private function createDataOld($allData,$jobInfo, &$jobRedisData, &$insertData){
        $platform=$allData['platform'];
        $dataJson=$allData['dataJson'];
        $videoList=$dataJson[$this->data];
        $videoModel= new DataVideo();
        foreach($videoList as $val){
            //视频评论、点赞、分享数
            $data['thumb_num'] = array_key_exists('likeCount',$val)?$val['videoInfo']:0;//点赞数
            $data['comment_num'] = array_key_exists('commentCount',$val)?$val['videoInfo']:0;//评论数
            $data['share_num'] = array_key_exists('shareCount',$val)?$val['videoInfo']:0;//分享数
            $data['watch_num'] = array_key_exists('watchCount',$val)?$val['videoInfo']:0;//播放数
            //验证视频是否符合采集需求
            /*$validateRes = $this->validateNum($data,$jobInfo);
            if ($validateRes == false) {
                continue;
            }*/

            $videoData['id']=com_create_guid();//生成唯一UUID

            $videoData['paltform']=$platform;
            $videoData['paltform_vid']=$val['aweme_id'];
            $videoData['paltform_uid']='';
            $videoData['paltform_uname']='';
            $videoData['paltform_uhead']='';

            //判断是否 已经存在
            $isExist = $videoModel->field('id')->where([
                'paltform_vid' => $videoData['paltform_vid']
            ])->find();
            if ($isExist) {
                continue;
            }


            $videoData['video_title']=$val['music']['title'];
            $videoData['videocover_link']=$val['video']['cover']['url_list'][0];
            $videoData['video_link']=$val['video']['bit_rate'][0]['play_addr']['url_list'][0];

            $videoData['video_duration'] = $val['video']['duration'] * 1000;//视频时长【微妙】

            $videoData['video_width']=$val['video']['width'];
            $videoData['video_height']=$val['video']['height'];

            $videoData['collect_num']=0;
            $videoData['unlike_num']=0;
            if ($videoData['video_duration']/1000 <= 90) {
                //$jobRedisData['smallvideo_num'] += 1;//小视频数量+1
                $videoData['is_small'] = 1;
            } else {
                //$jobRedisData['shortvideo_num'] += 1;//短视频数量+1
                $videoData['is_small'] = 0;
            }
            $videoData['validity_period']='';
            $videoData['video_type']='';
            $videoData['indescription']='';
            $videoData['video_tag']='';
            $videoData['publish_date']=date('Y-m-d H:i:s',$val['create_time']);
            $videoData['share_url']=$val['share_url'];
            $videoData['video_widhei_type'] = getVideoSizeType($videoData['video_width'], $videoData['video_height']);//判断视频宽高类型



            $videoData['create_by']='';
            $videoData['create_date']=date('Y-m-d H:i:s');
            $videoData['update_by']='';
            $videoData['update_date']=date('Y-m-d H:i:s');

            $insertData[] = $videoData;

        }

        $videoModel->isUpdate(false)->saveAll($insertData, false);
    }
    /**
     * 验证采集数据是否符合条件
     *
     * @param $data
     * @param $jobInfo
     * @return bool
     */
    private function validateNum($data,$jobInfo){
        $res = true;
        $keys = array_keys($data);
        foreach ($keys as $val){
            if($jobInfo[$val]>$data[$val]){
                $res = false;
                break;
            }
        }
        return $res;
    }
}